<template  #header>
  <el-tabs type="border-card" v-model="activeName" :before-leave="changeTab">
    <el-tab-pane label="订单信息" name="orderManage">
      <template>
        <div class="card-header">
          <span>订单信息列表</span>
        </div>
      </template>
      <el-row :gutter="10">
         <el-input placeholder="搜索编号或客户名称"  style="width: 180px;margin-right:10px;"  v-model="searchContent" ></el-input> 
        
          <el-button size="small" type="primary" @click="handlerSearch">搜索</el-button>
          <el-button size="small" type="primary" @click="showAddOrderDialog">添加</el-button>
          
       
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        highlight-current-row
        row-key="id"
        @row-dblclick="showOrderDetail"
        @current-change="currentRowSelect"
      >
        <el-table-column prop="orderNo" label="订单编号" />
        <el-table-column prop="customerName" label="客户名称" />
      
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus == 0">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="warning" v-else-if="scope.row.orderStatus == 1">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="success" v-else-if="scope.row.orderStatus == 2">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="danger" v-else>{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
          </template>
        </el-table-column>
         <el-table-column prop="businessName" label="业务员" />
          <el-table-column prop="orderDate" label="下单日期" />
        <el-table-column prop="reviewerName" label="审核人" width="150">
            <template #default="scope">
              {{scope.row.reviewerName}}<el-button v-if="scope.row.orderStatus == 0" @click="submitOrder(scope.row)" size="mini" style="margin-left:10px;" type="primary">提交</el-button>
            </template>
          </el-table-column>
        <el-table-column prop="orderVerify" label="审核日期" />
        <el-table-column prop="deposit" label="定金" />
        <el-table-column prop="depositer" label="定金收款人" />
            <!-- <el-table-column prop="deliveryType" label="发货方式" />
        <el-table-column prop="logistics" label="物流/快递编号" />
         <el-table-column prop="installer" label="安装人员" /> -->
        <el-table-column prop="createDate" label="创建时间" /> 
        <el-table-column label="操作" width="170"  >
          <template #default="scope" >
             <el-tooltip content="编辑" placement="top" v-if="scope.row.orderStatus == 0">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button></el-tooltip>
             <el-tooltip content="删除" placement="top" v-if="scope.row.orderStatus == 0">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.$index, scope.row)"
            ></el-button></el-tooltip>
            
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right; margin-top: 10px"
        :currentPage="currentPage"
        :page-size="10"
        :page-sizes="[10, 20, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
      <OrderAdd
        :centerDialogVisible="centerDialogVisible"
        @onCloseDialog="closeDialogVisible()"
      ></OrderAdd>
      <OrderEdit
        v-if="editDialogVisible === true"
        :orderId="id"
        :editDialogVisible="editDialogVisible"
        @onEditCloseDialog="closeEditDialogVisible"
      ></OrderEdit>
    </el-tab-pane>
    <el-tab-pane label="订单细项" name="orderDetailManage">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-button
          v-if="currentState === 0"
            type="primary"
            style="margin-bottom: 10px"
            @click="handleOrderDetail"
            >添加细项</el-button
          >
        </el-col>
      </el-row>

       <el-table :data="orderDetailData"  highlight-current-row
        row-key="id" style="width: 100%">
        <el-table-column prop="product.name" label="订购商品" />
        <el-table-column prop="product.code" label="订购商品" />
        <el-table-column prop="product.unitName" label="订购商品" />
         <el-table-column prop="orderCount" label="订购数量" />
         <el-table-column prop="actualCount" label="出货数量" />
        <el-table-column prop="price" label="单价" />
         <el-table-column prop="amountPrice" label="金额" />
         <el-table-column prop="shipper" label="出货人" />
         <el-table-column prop="shipperTime" label="出货时间" />
        <el-table-column label="操作" width="160" v-if="currentState === 0">
          <template #default="scope">
       
             <el-button
              size="mini"
              @click="handleEditOrderDetail(scope.$index, scope.row)"
              type="primary"
               icon="el-icon-edit" circle
              ></el-button>  
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteOrderDetail(scope.$index, scope.row)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
            
          </template>
        </el-table-column>
      </el-table>  
      <AddDetail
        v-if="orderDetailDialogVisible === true"
        :orderId="id"
        :orderNo="orderNo"
        :orderDetailDialogVisible="orderDetailDialogVisible"
        @onCloseOrderDetailVisible="closeOrderDetailDialogVisible"
      ></AddDetail>
      <EditDetail
        v-if="orderDetailEditDialogVisible === true"
        :orderDetailId="orderDetailId"
        :orderNo="orderNo"
        :orderDetailEditDialogVisible="orderDetailEditDialogVisible"
        @onCloseEditOrderDetailVisible="closeEditOrderDetailDialogVisible"
      ></EditDetail>
    </el-tab-pane>

 <el-tab-pane label="待审核订单" name="orderReviewManage">
   <el-table :data="reviewData"  highlight-current-row
        row-key="id" style="width: 100%">
    <el-table-column prop="orderNo" label="订单编号" />
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus == 0">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="warning" v-else-if="scope.row.orderStatus == 1">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="success" v-else-if="scope.row.orderStatus == 2">{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
            <el-tag type="danger" v-else>{{
              orderStatusList[scope.row.orderStatus].label
            }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="订单类型" > <template #default="scope">{{orderTypeList[scope.row.orderType].label}}</template></el-table-column>
         <el-table-column prop="businessName" label="业务员" />
          <el-table-column prop="orderDate" label="下单日期" />
        <el-table-column prop="reviewerName" label="审核人" width="150">
            <template #default="scope">
              {{scope.row.reviewerName}}
            </template>
          </el-table-column>
        <el-table-column prop="orderVerify" label="审核日期" />
        <el-table-column prop="deposit" label="定金" />
        <el-table-column prop="sumPrice" label="税价合计" />
            <!-- <el-table-column prop="deliveryType" label="发货方式" />
        <el-table-column prop="logistics" label="物流/快递编号" />
         <el-table-column prop="installer" label="安装人员" /> -->
        <el-table-column prop="createDate" label="创建时间" /> 
        <el-table-column label="操作" width="80" >
          <template #default="scope">
       
             <el-button
              size="mini"
              v-if="userinfo.id == scope.row.reviewerId"
              @click="reviewOrder(scope.$index, scope.row)"
              type="primary"
              
              >审核</el-button>  
              </template>
              </el-table-column>
        </el-table>
        <ReviewOrder v-if="reviewOrderVisible === true" @onCloseReviewDialag="closeReviewDialag"
        :reviewOrderId="reviewOrderId"
        :reviewOrderVisible="reviewOrderVisible"
        ></ReviewOrder>
 </el-tab-pane>

  </el-tabs>
</template>

<script>
import { reactive, toRefs, onMounted } from "vue";
import OrderAdd from "@/components/ord/OrderAdd.vue";
import OrderEdit from "@/components/ord/OrderEdit.vue";
import AddDetail from "../../components/ord/AddDetail.vue";
import EditDetail from "../../components/ord/EditDetail.vue";
import ReviewOrder from "../../components/ord/ReviewOrder.vue";
import {
  useHandlerEdit,
  useHandleSizeChange,
  useHandleCurrentChange,
  useHandlerSearch,
  useDelete,
  loadData,
  getRequest,
  deleteRequest,
  putRequest
} from "../../utils/api";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
 

export default {
  name: "SysOrder",
  components: {
    OrderAdd,
    OrderEdit,
    AddDetail,
    EditDetail,
    ReviewOrder
},

  setup(props, { emit }) {
    const baseUrl = "/order/basic/";
    const state = reactive({
      orderStatusList: [
        {value: 0,label: "待提交"},
        {value: 1,label: "待审核"},
        {value: 2,label: "审核通过"},
        {value: 3,label: "审核不通过"},
        {value: 4,label: "制单"},
        {value: 5,label: "待发货"},
        {value: 6,label: "安装调试完毕"},
         {value:7,label: "待收尾款"},
         {value:8,label: "订单完成"}
      ],
       orderTypeList:[ {value: 0,label: "直销"},
        {value: 1,label: "维修"},
        {value: 2,label: "调换"},
         {value: 3,label: "补发"}],
      searchContent: "",
      tableData: [],
      reviewData:[],
      orderDetailData: [],
      centerDialogVisible: false,
      editDialogVisible: false,
      orderDetailDialogVisible: false,
      orderDetailEditDialogVisible: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      id: "",
      baseUrl,
      orderName: "",
      activeName: "orderManage",
      orderDetailId: "",
      currentState: "",
      orderNo:'',
       userinfo: JSON.parse(window.sessionStorage.getItem("user")),
      reviewOrderVisible:false,
      reviewOrderId:'',
    });

    const showOrderDetail = (row, column, event) => {
      state.activeName = "orderDetailManage";
      state.id = row.id;
      state.orderNo = row.orderNo;
      state.currentState = row.orderStatus ;
    };
  //加载订单细项数据
    const loadOrderDetailData = () => {
      getRequest("/order/basic/detail/", { id: state.id }).then(
        (response) => {
          if (response) {
            state.orderDetailData = response.data;
          }
        }
      );
    };
  //加载待审核数据
    const loadReviewData=()=>{
         getRequest("/order/basic/review").then(
        (response) => {
          if (response) {
            state.reviewData = response.data;
          }
        }
      );
    }

    //处理标记信息 标记后数据会显示红旗 并且排在前面
    // const handleFlag = (orderId) => {
    //   putRequest(`/order/basic/status/${orderId}`).then((res) => {
    //     if (res) {
    //       loadData(state, state.baseUrl);
    //       ElMessage.success({
    //         type: "success",
    //         title: "成功",
    //         message: "操作成功",
    //         duration: 2000,
    //       });
    //     }
    //   });
    // };

    const showAddOrderDialog = () => {
      state.centerDialogVisible = true;
    };

    const closeDialogVisible = (visible, data) => {
      state.centerDialogVisible = false;
      loadData(state, state.baseUrl);
    };

    const closeEditDialogVisible = (visible, data) => {
      state.editDialogVisible = visible;

      if (data !== undefined) {
        loadData(state, state.baseUrl);
      }
    };

    const closeOrderDetailDialogVisible = (visible, data) => {
      state.orderDetailDialogVisible = visible;
      if (data !== undefined) {
        loadOrderDetailData();
      }
    };

    const closeEditOrderDetailDialogVisible = (visible, data) => {
      state.orderDetailEditDialogVisible = visible;
      if (data !== undefined) {
        loadOrderDetailData();
      }
    };

    const handleEditOrderDetail = (index, row) => {
      state.orderDetailId = row.id;
      state.orderDetailEditDialogVisible = true;
    };

    const handleDeleteOrderDetail = (index, row) => {
      ElMessageBox.confirm("你确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        callback: (action) => {
          if ("confirm" === action) {
            deleteRequest("/order/basic/detail/", { id: row.id }).then(
              (response) => {
                if (response.code == 200) {
                  loadOrderDetailData();
                  ElNotification({
                    type: "success",
                    title: "成功",
                    message: "删除成功",
                    duration: 2000,
                  });
                }
              },
              (error) => {
                ElNotification({
                  type: "error",
                  title: "失败",
                  message: "删除失败",
                  duration: 2000,
                });
              }
            );
          }
        },
      });
    };

    

    const currentChange = (pageNo) => {
      state.currentPage = pageNo;
      loadData(state, state.baseUrl);
    };
 
    const handleOrderDetail = () => {
      state.orderDetailDialogVisible = true;
    };

    const currentRowSelect = (currentRow, oldCurrentRow) => {
      state.id = currentRow.id;
      state.currentState = currentRow.orderStatus;
      state.orderNo = currentRow.orderNo;
   
    };

    const submitOrder = (row)=>{
      if(row.orderStatus==0){
       ElMessageBox.confirm("你确定要【提交审核】吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        callback: (action) => {
          if ("confirm" === action) {
            putRequest(`/order/basic/${row.id}`).then(
              (response) => {
                if (response.code == 200) {
                   loadData(state, state.baseUrl);
                  ElNotification({
                    type: "success",
                    title: "成功",
                    message: "操作成功",
                    duration: 2000,
                  });
                }
              },
              (error) => {
                ElNotification({
                  type: "error",
                  title: "失败",
                  message: "操作失败",
                  duration: 2000,
                });
              }
            );
          }
        },
      });
      }else{
         ElNotification({
                  type: "error",
                  title: "失败",
                  message: "操作失败",
                  duration: 2000,
                });
              }
      
      
    }
 
    const changeTab = (activeName, oldActiveName) => {
      return new Promise((resolve, reject) => {
        if (activeName == "orderDetailManage") {
          if (state.id) {
            loadOrderDetailData();
            return resolve();
          } else {
            ElMessage.error("请选中某一行订单信息！");
            return reject();
          }
        }else if(activeName == "orderReviewManage"){
          loadReviewData()
          return resolve();
        }else{
            return resolve();
        }
       
      });
    };
 
  const reviewOrder=(index,row)=>{
      state.reviewOrderVisible=true ;
      state.reviewOrderId = row.id ;
     
  }

  const closeReviewDialag = ()=>{
    state.reviewOrderVisible=false ;
    loadReviewData() ;
  }

    onMounted(() => {
     loadData(state, state.baseUrl);
    });
    return {
      ...toRefs(state), //解构响应式数据
      ...useDelete(state, baseUrl),
      ...useHandlerSearch(state, baseUrl),
      ...useHandlerEdit(state),
      ...useHandleSizeChange(state, baseUrl),
      ...useHandleCurrentChange(state, baseUrl),
      
      showAddOrderDialog,
      closeDialogVisible,
      closeEditDialogVisible,
      currentChange,
      handleOrderDetail,
      closeOrderDetailDialogVisible,
      currentRowSelect,
      showOrderDetail,
      changeTab,
      closeEditOrderDetailDialogVisible,
      handleEditOrderDetail,
      handleDeleteOrderDetail,
      submitOrder,
      reviewOrder,
      closeReviewDialag
      // handleFlag,
      
    };
  },
};
</script>
<style scoped>
</style>